package com.rkc.component.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.rkc.component.FileService;
import com.rkc.config.OSSConfiguration;
import com.rkc.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author `RKC`
 * @date 2021/10/15 15:08
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private OSSConfiguration ossConfiguration;

    @Override
    public String upload(MultipartFile multipartFile) {
        //创建OSS对象
        OSS ossClient = new OSSClientBuilder().build(ossConfiguration.getEndpoint(), ossConfiguration.getAccessKeyId(),
                ossConfiguration.getAccessSecret());
        String originalFilename = multipartFile.getOriginalFilename();
        //jdk8格式化日期
        LocalDateTime ldt = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String folder = dtf.format(ldt);
        //拼接路径，oss存储的路径 user/2021/10/15/xafasdf.png
        String filename = CommonUtil.generateUUID();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        //指定oss上的user文件夹
        String finalFilename = "user/" + folder + "/" + filename + extension;
        try {
            PutObjectResult por = ossClient.putObject(ossConfiguration.getBucketName(), finalFilename, multipartFile.getInputStream());
            //拼装返回路径
            if (por != null) {
                return "https://" + ossConfiguration.getBucketName() + "." + ossConfiguration.getEndpoint() + "/" + finalFilename;
            }
        } catch (IOException e) {
            log.error("文件上传失败：{}", e.toString());
        } finally {
            //oss关闭服务
            ossClient.shutdown();
        }
        return null;
    }
}
